<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Laravel\Lumen\Routing\Controller as BaseController;

class Controller extends BaseController
{
    //
    public function __construct(Request $request)
    {
        try{
            //判断登录状态是否过期
            $uid = $request->input('userId', '');
            if($uid){
                $startTime = strtotime(date("Y-m-d")." 00:00:00");
                $endTime = strtotime(date("Y-m-d")." 23:59:59");
                $isLogin = DB::table('login_token')->where([['users_id','=',$uid]])
                    ->whereBetween('time',[$startTime,$endTime])->value('id');
                if(empty($isLogin)){
                    echo json_encode(['success'=>false,'code'=>8888,'message'=>'token失效']);exit;
                }
            }
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }

    /**
     * SendTemplate 触发模板通知
     *
     * @return reposne
     */
    public function SendTemplate($userId,$type,$keyword1,$keyword2,$keyword3,$keyword4,$id='')
    {
        //查询用户信息
        $info = DB::table('users')->where('id','=',$userId)->first();
        if(!$info->open_id){
            return 1001;
        }
        //查询formId
        $time = time()-604800;//7天之前的
        $formId = DB::table('users_formid')->where([['users_id','=',$userId],['is_use','=','2'],['time','>',$time]])->value('form_id');
        if(!$formId){
            return 1002;
        }
        switch ($type)
        {
            case 1:
                $template = array(
                    'touser' => $info->open_id,
                    'template_id' => '6VrrsQli026nNz9LI9RqPWBtv_Fqpp12qnser5uZ98g',
                    'page' => '/pages/start/start?page=find_detail&find_id='.$id,
                    'form_id'=>$formId,
                    'topcolor' =>'#7B68EE',
                    'data' => array(
                        'keyword1'  => array('value'=>$keyword1,'color'=>'#000000'),
                        'keyword2'  => array('value'=>$keyword2,'color'=>'#000000'),
                        'keyword3'  => array('value'=>$keyword3,'color'=>'#000000'),
                        'keyword4'  => array('value'=>$keyword4,'color'=>'#000000'),
                    )
                );
                break;
            case 2:
                $template = array(
                    'touser' => $info->open_id,
                    'template_id' => 'HzmMv0eVk8mE85AB3T84CLafDvIGVPv3XLoI3kywfxM',
                    'page' => '/pages/start/start?page=supplier_detail&supplier_id='.$id,
                    'form_id'=>$formId,
                    'topcolor' =>'#7B68EE',
                    'data' => array(
                        'keyword1'  => array('value'=>$keyword1,'color'=>'#000000'),
                        'keyword2'  => array('value'=>$keyword2,'color'=>'#000000'),
                        'keyword3'  => array('value'=>$keyword3,'color'=>'#000000'),
                        'keyword4'  => array('value'=>$keyword4,'color'=>'#000000'),
                    )
                );
                break;
            case 3:
                $template = array(
                    'touser' => $info->open_id,
                    'template_id' => '_GwVb33lqkmFtENJNk_ux6ut-YlhlPHpckEayhN1Ogw',
                    'page' => '/pages/start/start?page=diamond_list',
                    'form_id'=>$formId,
                    'topcolor' =>'#7B68EE',
                    'data' => array(
                        'keyword1'  => array('value'=>$keyword1,'color'=>'#000000'),
                        'keyword2'  => array('value'=>$keyword2,'color'=>'#000000'),
                        'keyword3'  => array('value'=>$keyword3,'color'=>'#000000'),
                        'keyword4'  => array('value'=>$keyword4,'color'=>'#000000'),
                    )
                );
                break;
            default:
                $template = array();
        }
        if(empty($template)){
            return 1003;
        }
        $appid = env('APP_ID');
        $secret = env('APP_SECRET');
        $url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";

        $access_token=self::httpGet($url);

        $access_token=json_decode($access_token)->access_token;

        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$access_token";

        $template =  json_encode($template);

        $result = json_decode(self::httpPost($url,$template));
        if($result->errcode == 0){
            DB::table('users_formid')->where('form_id','=',$formId)->update(array('is_use'=>1,'use_time'=>time()));
            return 1000;
        }elseif($result->errcode == 41028 || $result->errcode == 41029){
            //已过期
            DB::table('users_formid')->where('form_id','=',$formId)->update(array('is_use'=>1,'use_time'=>time()));
            return 1004;
        }else{
            return $result->errcode;
        }
//        print_r($result);
//        return $result;

    }

    public function httpGet($url){
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo;    //返回json对象
    }

    public function httpPost($url,$data)
    {

        if( empty( $url ) ){
            return false;
        }
        $post = $data;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($post)));
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}
